package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CommunityAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.ThreadManager;
import com.voicechat.firstmet.utils.Utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: OtherDynamicPageActivity
 * @Description: 他人动态页面
 * @Author: ljp
 * @CreateDate: 2018/10/31 9:18
 * @Version: 1.0
 */
public class OtherDynamicPageActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.recycler_dynamic_page)
    RecyclerView recyclerDynamicPage;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.linear_layout)
    LinearLayout linearLayout;
    private String anchorId;
    private String token;
    private String deviceInfo;
    private String userId;
    private int page;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private List<PostBean.PageBean.ListBean> postBeans;
    private CommunityAdapter communityAdapter;
    private Runnable runnable;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_other_dynamic;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        anchorId = getIntent().getStringExtra("anchorId");
        initView();
        setHttpData();
    }

    /**
     * @return
     * @method
     * @description 网络数据请求
     * @date: 2018/10/30 19:40
     * @author: ljp
     */
    private void setHttpData() {
        MeInfoService.dynamicPage(token, deviceInfo, userId, anchorId, page + "", "10").subscribe(postBean -> {
            if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = postBean.getPage().getCount() / postBean.getPage().getPageSize() +
                        (postBean.getPage().getCount() % postBean.getPage().getPageSize() == 0 ? 0 : 1);
                //int i = postBean.getPage().getCount() % postBean.getPage().getPageSize();
                if (i != 0 && page > i) {//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        postBeans.clear();
                        smartRefresh.finishRefresh();
                    }
                    if(postBean.getPage().getList() != null) {
                        smartRefresh.setVisibility(View.VISIBLE);
                        postBeans.addAll(postBean.getPage().getList());
                        communityAdapter.notifyDataSetChanged();
                        setThreadPost(postBean.getPage().getList());
                    }else {
                        linearLayout.setVisibility(View.VISIBLE);
                    }
                    smartRefresh.finishLoadMore();

                }
            } else if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(postBean.getMsg());
            }
        }, throwable -> {

        });

    }

    /**
     * @return
     * @method
     * @description 启动线程池下载语音信息
     * @date: 2018/10/16 14:30
     * @author: ljp
     */
    private void setThreadPost(List<PostBean.PageBean.ListBean> postBeans) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < postBeans.size(); i++) {
                    if (!TextUtils.isEmpty(postBeans.get(i).getVoiceUrl())) {
                        String voiceInfo = postBeans.get(i).getVoiceUrl();
                        int finalI = i;
                        OssClient.getInstance().init(context).fileDownload(voiceInfo, new OssClient.OnDownloadFile() {
                            @Override
                            public void onDownFileSuccess(InputStream inputStream) {
                                String voiceName = Utils.getVoiceName(postBeans.get(finalI).getVoiceUrl());
                                //Log.i(TAG, "onDownFileSuccess: ---------"+voiceName);
                                String path = ConstantSet.VOICEINTR;
                                try {
                                    OssConfig.writeToLocalPost(path, inputStream, voiceName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onDownFileProgress(String progress) {
                                //Log.i(TAG, "onDownFileProgress: ----------"+progress);
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * @return
     * @method
     * @description 数据实例化
     * @date: 2018/10/30 16:48
     * @author: ljp
     */
    private void initView() {
        postBeans = new ArrayList<>();
        page = 1;
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                setHttpData();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                setHttpData();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        communityAdapter = new CommunityAdapter(context, postBeans, R.layout.item1_community, "person");
        recyclerDynamicPage.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerDynamicPage.setAdapter(communityAdapter);
        communityAdapter.setItemSetClick(new CommunityAdapter.ItemSetClick() {
            @Override
            public void setIconClick(View view, PostBean.PageBean.ListBean listBean) {

            }

            @Override
            public void setIconClick(View view, CommBean.MapBean.DynamicBean dynamic) {

            }

            @Override
            public void setItemClick(View view, PostBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PostDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);

            }

            @Override
            public void setLikeClick(View view, CommBean.MapBean.DynamicBean dynamic) {

            }

            @Override
            public void setLikeClick(View view, PostBean.PageBean.ListBean listBean) {
                CommunityService.postLikeAndUnLike(token,deviceInfo,listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE,userId).subscribe(result -> {
                    if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                        if(listBean.getIsFabulous().equals("0")){//0未点赞 1 点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount()+1);
                        }else if(listBean.getIsFabulous().equals("1")){
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount()-1);
                        }
                        communityAdapter.notifyDataSetChanged();
                    }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    }else {
                        toast_MakeText(result.getMsg());
                    }
                    // Log.i(TAG, "setLikeClick: -------"+result.toString());
                },throwable -> {
                    // Log.i(TAG, "setLikeClick: -------"+throwable.toString());
                });
            }

            @Override
            public void setItemClick(View view, CommBean.MapBean.DynamicBean dynamic) {

            }

            @Override
            public void setNoticeClick(View view, List<CoummunityNotice.PageBean.ListBean> notices) {

            }

            @Override
            public void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, View view, int position,View imagePlay) {
                String path = ConstantSet.VOICEINTR + ConstantSet.VOICE_POST + Utils.getVoiceName(listBean.getVoiceUrl());
                //Log.i(TAG, "onBindViewHolder: -----" + path);
                if (FileUtils.isExists(path)) {
                    try {
                        player(path, (ImageView) view, position);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void setPlayVoiceClick(CommBean.MapBean.DynamicBean dynamic, View view, int position) {

            }

            @Override
            public void setItemClickShare(View view, PostBean.PageBean.ListBean listBean) {
                UMWeb web = new UMWeb(HTTPAPI.URL_SHARE+"id="+listBean.getId()+"&userId="+listBean.getUserId());
                String[] list = getResources().getStringArray(R.array.share_title);
                Random random = new Random();
                web.setTitle(list[random.nextInt(list.length)]);//标题
                if (!TextUtils.isEmpty(listBean.getUrl())) {
                    String[] strings = Utils.spitPictureUrl(listBean.getUrl());
                    web.setThumb(new UMImage(activity, OssConfig.OSS_HTTP+strings[0]));  //缩略图
                }
                web.setDescription(listBean.getContent());//描述
                new ShareAction(activity).withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {
                            }
                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                Toast.makeText(activity,getResources().getString(R.string.share_success),Toast.LENGTH_LONG).show();
                            }
                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                Toast.makeText(activity,getResources().getString(R.string.share_fial),Toast.LENGTH_LONG).show();
                            }
                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {
                                Toast.makeText(activity,getResources().getString(R.string.share_cacal),Toast.LENGTH_LONG).show();
                            }
                        }).open();
            }

        });
    }

    int mFirstVoicePlayItem;//第一级列表的喇叭动画初始位置
    int mSecondVoicePlayItem;//第二级列表的喇叭动画初始位置
    //int position;//当前列表的位置
    AnimationDrawable animationDrawable;

    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player(String path, ImageView imageView, int position) throws FileNotFoundException {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        mSecondVoicePlayItem = -1;
        if (animationDrawable != null) {
            MediaUtil.getInstance().stop();
            animationDrawable.stop();
            animationDrawable.selectDrawable(2);
            animationDrawable = null;
            if (mFirstVoicePlayItem != position) {
                mFirstVoicePlayItem = position;
                imageView.setImageResource(R.drawable.post_voice);
                animationDrawable = (AnimationDrawable) imageView.getDrawable();
                animationDrawable.start();
                MediaUtil.getInstance().play(new FileInputStream(path));
            }
        } else {
            mFirstVoicePlayItem = position;
            imageView.setImageResource(R.drawable.post_voice);
            animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();
            MediaUtil.getInstance().play(new FileInputStream(path));
        }
        MediaUtil.getInstance().getPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                if(animationDrawable != null) {
                    animationDrawable.stop();
                    animationDrawable.selectDrawable(2);
                    animationDrawable = null;
                }

            }
        });
    }

    @OnClick(R.id.linear_back)
    public void onClick() {
        finish();
    }
}
